<template>
  <pro-layout
    :menus="menus"
    :collapsed="collapsed"
    :mediaQuery="query"
    :isMobile="isMobile"
    :handleMediaQuery="handleMediaQuery"
    :handleCollapse="handleCollapse"
    :i18nRender="i18nRender"
    v-bind="settings"
  >
    <!-- Ads begin
      广告代码 真实项目中请移除
      production remove this Ads
    -->
    <ads v-if="isProPreviewSite && !collapsed"/>
    <!-- Ads end -->

    <!-- 1.0.0+ 版本 pro-layout 提供 API，
          我们推荐使用这种方式进行 LOGO 和 title 自定义
    -->
    <template v-slot:menuHeaderRender>
      <div class="flex flexCenter" @click.stop="changeCompany">
        <h1 style="margin-left: 0"><ellipsis :length="12" tooltip>{{ title }}</ellipsis></h1>
        <a-button style="margin-left: 20px" v-if="companyList.length > 1" type='primary' @click.stop="changeCompany">切换</a-button>
      </div>
    </template>
    <!-- 1.0.0+ 版本 pro-layout 提供 API,
          增加 Header 左侧内容区自定义
    -->
    <!-- <template v-slot:headerContentRender>
      <div>
        <a-tooltip title="刷新页面">
          <a-icon type="reload" style="font-size: 18px;cursor: pointer;" @click="() => { $message.info('只是一个DEMO') }" />
        </a-tooltip>
      </div>
    </template> -->

    <setting-drawer v-if="isDev" :settings="settings" @change="handleSettingChange">
      <div style="margin: 12px 0;">
        This is SettingDrawer custom footer content.
      </div>
    </setting-drawer>
    <template v-slot:rightContentRender>
      <right-content :top-menu="settings.layout === 'topmenu'" :is-mobile="isMobile" :theme="settings.theme" />
    </template>
    <!-- custom footer / 自定义Footer -->
    <!-- <template v-slot:footerRender>
      <global-footer />
    </template> -->
    <router-view />


    <a-modal 
      v-model="visible" 
      title="切换企业"
      @ok="handleOk" 
      :forceRender="true"
      @cancel="visible = false">
        <div>
          <div v-for="(item) in companyList" :key="item.id">
            <div class="flex spaceBetween" style="margin-bottom: 20px;padding: 0 20px" @click="selCompany(item)">
              <div style="font-size: 16px;color: #333">{{item.companyName}}</div>
              <a v-if="selCompanyId == item.id" href="javascript:void(0)"><a-icon style="font-size: 20px" type="check-circle" /></a>
              <a-icon v-else style="font-size: 20px;color: #AAA" type="check-circle" />
            </div>
          </div>
        </div>
    </a-modal>
  </pro-layout>
</template>

<script>
import { SettingDrawer, updateTheme } from '@ant-design-vue/pro-layout'
import { i18nRender } from '@/locales'
import { mapState } from 'vuex'
import { asyncRouterMap } from '@/config/router.config.js'
import { CONTENT_WIDTH_TYPE, SIDEBAR_TYPE, TOGGLE_MOBILE_TYPE , USER_TYPE } from '@/store/mutation-types';
import { queryLaborCompany , changeLaborCompany } from '@/api/services/company';
import { getUserCustomerList , changeCustomer } from '@/api/companys';
import { Ellipsis } from '@/components';

import defaultSettings from '@/config/defaultSettings'
import RightContent from '@/components/GlobalHeader/RightContent'
import GlobalFooter from '@/components/GlobalFooter'
import Ads from '@/components/Other/CarbonAds'
import LogoSvg from '../assets/logo.svg?inline'
import storage from 'store'

export default {
  name: 'BasicLayout',
  components: {
    SettingDrawer,
    RightContent,
    GlobalFooter,
    LogoSvg,
    Ads,
    Ellipsis,
  },
  data () {
    return {
      // preview.pro.antdv.com only use.
      isProPreviewSite: process.env.VUE_APP_PREVIEW === 'true' && process.env.NODE_ENV !== 'development',
      // end
      isDev: process.env.NODE_ENV === 'development' || process.env.VUE_APP_PREVIEW === 'true',

      // base
      menus: [],
      // 侧栏收起状态
      collapsed: false,
      title: defaultSettings.title,
      settings: {
        // 布局类型
        layout: defaultSettings.layout, // 'sidemenu', 'topmenu'
        // CONTENT_WIDTH_TYPE
        contentWidth: defaultSettings.layout === 'sidemenu' ? CONTENT_WIDTH_TYPE.Fluid : defaultSettings.contentWidth,
        // 主题 'dark' | 'light'
        theme: defaultSettings.navTheme,
        // 主色调
        primaryColor: defaultSettings.primaryColor,
        fixedHeader: defaultSettings.fixedHeader,
        fixSiderbar: defaultSettings.fixSiderbar,
        colorWeak: defaultSettings.colorWeak,

        hideHintAlert: false,
        hideCopyButton: false
      },
      // 媒体查询
      query: {},

      // 是否手机模式
      isMobile: false,
      userType: 2,
      companyList: [],
      visible: false,
      selCompanyId: '',
    }
  },
  computed: {
    ...mapState({
      // 动态主路由
      mainMenu: state => state.permission.addRouters
    })
  },
  created () {
    // const routes = this.mainMenu.find(item => item.path === '/')
    const routes = asyncRouterMap.find((item) => item.path === '/')
    this.menus = (routes && routes.children) || []
    // 处理侧栏收起状态
    this.$watch('collapsed', () => {
      this.$store.commit(SIDEBAR_TYPE, this.collapsed)
    })
    this.$watch('isMobile', () => {
      this.$store.commit(TOGGLE_MOBILE_TYPE, this.isMobile)
    })
    this.userType = sessionStorage.getItem(USER_TYPE);
    if(this.userType == 2){
      this.queryLaborCompanyList();
    }else if(this.userType == 3){
      this.queryCustomerList();
    }
  },
  mounted () {
    const userAgent = navigator.userAgent
    if (userAgent.indexOf('Edge') > -1) {
      this.$nextTick(() => {
        this.collapsed = !this.collapsed
        setTimeout(() => {
          this.collapsed = !this.collapsed
        }, 16)
      })
    }

    // first update color
    // TIPS: THEME COLOR HANDLER!! PLEASE CHECK THAT!!
    if (process.env.NODE_ENV !== 'production' || process.env.VUE_APP_PREVIEW === 'true') {
      updateTheme(this.settings.primaryColor)
    }
    var logoA = document.querySelector('.ant-pro-sider-menu-logo .router-link-active')
    console.log(logoA.href,'logoA')
    logoA.setAttribute("href", "javascript:void(0)");
  },
  methods: {
    i18nRender,
    handleMediaQuery (val) {
      this.query = val
      if (this.isMobile && !val['screen-xs']) {
        this.isMobile = false
        return
      }
      if (!this.isMobile && val['screen-xs']) {
        this.isMobile = true
        this.collapsed = false
        this.settings.contentWidth = CONTENT_WIDTH_TYPE.Fluid
        // this.settings.fixSiderbar = false
      }
    },
    handleCollapse (val) {
      this.collapsed = val
    },
    handleSettingChange ({ type, value }) {
      console.log('type', type, value)
      type && (this.settings[type] = value)
      switch (type) {
        case 'contentWidth':
          this.settings[type] = value
          break
        case 'layout':
          if (value === 'sidemenu') {
            this.settings.contentWidth = CONTENT_WIDTH_TYPE.Fluid
          } else {
            this.settings.fixSiderbar = false
            this.settings.contentWidth = CONTENT_WIDTH_TYPE.Fixed
          }
          break
      }
    },
    // 获取劳务所有公司列表（切换公司）
    queryLaborCompanyList(){
      let _this = this;
      queryLaborCompany({})
      .then(res => {
        if(res.success){
          _this.companyList = res.data;
          var laborCompanyId = sessionStorage.getItem('laborCompanyId')
          var company = res.data.find(item => item.id == laborCompanyId);
          if(company.id){
            _this.title = company.companyName;
            _this.selCompanyId = company.id;
          }
        }else{
          _this.$notification['error']({
            message: '温馨提示',
            description: res.errMessage,
            duration: 8
          })
        }
      })
    },
    // 获取甲方所有公司列表（甲方切换公司）
    queryCustomerList(){
      let _this = this;
      getUserCustomerList({})
      .then(res => {
        if(res.success){
          _this.companyList = res.data;
          var customerId = sessionStorage.getItem('customerId')
          var company = res.data.find(item => item.id == customerId);
          if(company.id){
            _this.title = company.customerName;
            _this.selCompanyId = company.id;
          }
        }else{
          _this.$notification['error']({
            message: '温馨提示',
            description: res.errMessage,
            duration: 8
          })
        }
      })
    },
    // 切换企业
    changeCompany(){
      this.visible = true;
    },
    selCompany(item){
      this.selCompanyId = item.id;
    },
    handleOk(){
      let _this = this;
      var oldCompanyId = _this.userType == 2 ? sessionStorage.getItem('laborCompanyId') : sessionStorage.getItem('customerId');
      if(oldCompanyId == _this.selCompanyId){
        _this.$message.warning('当前企业已登录，无需切换')
        return;
      }
      var apiUrl = _this.userType == 2 ? changeLaborCompany(_this.selCompanyId) : changeCustomer(_this.selCompanyId);
      apiUrl.then(res => {
        if(res.success){
          _this.$notification['success']({
            message: '温馨提示',
            description: '切换成功',
            duration: 8
          })
          var paths = _this.userType == 2 ? '/servicesWorkBench/workBench' : '/companysProjects/projectsList';
          var company = _this.companyList.find(item => item.id == _this.selCompanyId);
          console.log(company,'company')
          sessionStorage.setItem('userName',company.userName)
          if(_this.userType == 2){
            sessionStorage.setItem('laborCompanyId',_this.selCompanyId)
          }else{
            sessionStorage.setItem('customerId',_this.selCompanyId)
          }
          location.reload()
          // _this.$router.push({ 'path': paths})
        }else{
          _this.$notification['error']({
            message: '温馨提示',
            description: res.errMessage,
            duration: 8
          })
        }
      })
    },
  }
}
</script>

<style lang="less">
@import "./BasicLayout.less";

.ant-pro-sider-menu-logo{
  padding-left: 0;
}
</style>
